package com.mediacloud.app.newsmodule.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.CommentCommitPushEvent;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.im.sdk.TXImManager;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.mmkv.MMKV;
import com.tencent.qcloud.tim.uikit.base.IMEventListener;
import com.tencent.qcloud.tim.uikit.component.AudioPlayer;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class NewAudioLiveActivity extends AudioLiveDetailActivityHalf {
    private String chatId;
    public ChatLayout chatLayout;
    public TIMConversation mConversation;
    TextView tvAnchorIcon;
    TextView tvAnchorName;
    boolean exeJoinRoom = false; //标记有没有执行进入房间的方法
    @Override
    public int getLayoutResID() {
        return R.layout.app_factory_activity_new_audio_player_chat;
    }

    @Override
    public boolean hasChatRoom() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        View programListButton = findViewById(R.id.programListButton);
        Drawable live_chat_list_shape = ContextCompat.getDrawable(this, R.drawable.live_chat_list_shape);
        live_chat_list_shape = Utility.tintDrawable(DefaultBgUtil.getTintColor(this), live_chat_list_shape);
        programListButton.setBackground(live_chat_list_shape);
        programListButton.setOnClickListener(v -> {
            Intent intent = new Intent(this, ChatLiveProgressListActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("data", articleItem);
            bundle.putInt("COLOR", getPaletteColor());
            bundle.putBoolean("fullScreen", true);
            bundle.putLong("START_LONG", startLong);
            bundle.putLong("END_LONG", endLong);
            intent.putExtras(bundle);
            startActivity(intent);

        });

        tvAnchorIcon = findViewById(R.id.tv_author_icon);
        tvAnchorName = mRootView.findViewById(R.id.tv_anchor_name);
        Drawable live_author_name_shape = ContextCompat.getDrawable(tvAnchorIcon.getContext(), R.drawable.live_author_name_shape);
        live_author_name_shape = Utility.tintDrawable(DefaultBgUtil.getTintColor(tvAnchorIcon.getContext()), live_author_name_shape);
        tvAnchorIcon.setBackground(live_author_name_shape);
        String author = getIntent().getStringExtra("AUTHOR"); //推送过来的
        if (author != null) {
            articleItem.Author = author;
        }
        if (!TextUtils.isEmpty(articleItem.Author) && articleItem.Author.length() > 2) {
            tvAnchorIcon.setText(articleItem.Author.substring(articleItem.Author.length() - 2));
        } else {
            tvAnchorIcon.setText(articleItem.Author);
        }
        tvAnchorName.setText(articleItem.Author);

        TextView textView = Utility.findViewById(mRootView, R.id.tv_live_statue);
        if (MMKV.defaultMMKV().getString("REPLAY_ID", "").equals("" + articleItem.getId())) {
            textView.setVisibility(View.VISIBLE);
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.live_author_name_shape);
            if (drawable instanceof GradientDrawable) {
                ((GradientDrawable) drawable).setColor(DefaultBgUtil.getTintColor(this));
            }
            textView.setBackground(drawable);
            textView.setText("回放");
        } else {
            textView.setVisibility(View.GONE);
        }

        chatLayout = findViewById(R.id.chat_layout);

        if (UserInfo.isLogin(this)) {
            try {
                chatLayout.initDefault();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            TXImManager.getInstance().addIMEventListener(new IMEventListener() {
                @Override
                public void onConnected() {
                    super.onConnected();
                    if (UserInfo.isLogin(NewAudioLiveActivity.this) && !exeJoinRoom) {
                        try {
                            chatLayout.initDefault();
                            setChatView();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        final InputLayout inputLayout = chatLayout.getInputLayout();
        inputLayout.setVisibility(View.GONE);
        broccoliLayout = findViewById(R.id.broccoliLayout4);
    }

    @Override
    protected void onAudioDetailCallBack(ArticleItemReciver data) {
        super.onAudioDetailCallBack(data);
        chatId = data.chatRoom.groupId;
        if (UserInfo.isLogin(this) && !exeJoinRoom) {
            setChatView();
        }
    }



    private void setChatView() {

        TIMGroupManager.getInstance().applyJoinGroup(chatId, "some reason", new TIMCallBack() {
            @java.lang.Override
            public void onError(int code, String desc) {
                //接口返回了错误码 code 和错误描述 desc，可用于原因
                //错误码 code 列表请参见错误码表
                Log.e(TAG, "applyJoinGroup err code = " + code + ", desc = " + desc);
                if (code == 10013) {//被邀请加入的用户已经是群成员
                    initChatInfo();
                } else {
                    TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("ALChatRoom", articleItem.getTitle());
                    param.setGroupId(chatId);
                    TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
                        @Override
                        public void onError(int i, String s) {
                            Log.e(TAG, "创群 onError" + s);
                        }

                        @Override
                        public void onSuccess(String s) {
                            Log.e(TAG, "创群 onSuccess");
                            initChatInfo();
                        }
                    });
                }
            }

            @java.lang.Override
            public void onSuccess() {
                Log.i(TAG, "applyJoinGroup success");
                initChatInfo();
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {

    }

    private void initChatInfo() {
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setId(chatId);
        chatInfo.setType(TIMConversationType.Group);
        getImUserInfo(chatInfo);
        chatLayout.setChatInfo(chatInfo);
        chatLayout.setBackgroundColor(0xFFF4F1F4);
        chatLayout.getTitleBar().setVisibility(View.GONE);
        chatLayout.getMessageLayout().setAvatarRadius(90);
    }

    private void getImUserInfo(ChatInfo chatInfo) {
        List<String> users = new ArrayList<>();
        users.add(chatInfo.getId());
        UserInfo userInfo = UserInfo.getUserInfo(this);
        users.add(userInfo.getUser_chat_id());

        //获取用户资料
        TIMFriendshipManager.getInstance().getUsersProfile(users, true, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int code, String desc) {
                Log.w(TAG, "TIMFriendshipManager onError " + " " + code + " " + desc);
            }

            @Override
            public void onSuccess(List<TIMUserProfile> result) {
                Log.w(TAG, "TIMFriendshipManager onSuccess ");
            }
        });
    }


    @Override
    public int getStatusBarColor() {
        String customDetailNavigateBgColor = AppFactoryGlobalConfig.getAppServerConfigInfo(this).getCustomDetailNavigateBgColor();
        if (!TextUtils.isEmpty(customDetailNavigateBgColor) && customDetailNavigateBgColor.startsWith("#")) {
            try {
                return Color.parseColor(customDetailNavigateBgColor);
            } catch (Exception e) {
            }
        }
        return AppFactoryGlobalConfig.getAppServerConfigInfo(this).getMainColor();
    }

    @Override
    protected List<View> getPaidViews() {
        return null;
    }

//    @Override
//    public void onComment(@NonNull String content, String beReplayUserName, String beReplayUserId) {
//        super.onComment(content, beReplayUserName, beReplayUserId);
//        commentDialogFram.dismiss();
//        setMessage(content);
//        commentDialogFram.commentInputText.getText().clear();
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    private void commentCommitPush(CommentCommitPushEvent data) {
        setMessage(data.getContent());
    }
    private void setMessage(String content) {
        MessageInfo msg = MessageInfoUtil.buildTextMessage(content);
        sendGroupTips(msg);
    }


    private void sendGroupTips(MessageInfo message) {
        if (mConversation == null)
            mConversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, chatId);

        mConversation.sendMessage(message.getTIMMessage(), new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int code, String desc) {

            }

            @Override
            public void onSuccess(TIMMessage timMessage) {

                List<TIMMessage> msgs = new ArrayList<>();
                msgs.add(message.getTIMMessage());
                GroupChatManagerKit.getInstance().onNewMessages(msgs);
            }
        });

    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        AudioPlayer.getInstance().setVolumeListener(null);
        super.onDestroy();
    }
}
